<script setup lang="ts">
import { PropType, watch, ref, reactive } from 'vue'
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { required } from '@/utils/formRules'

import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()

const props = defineProps({
  formData: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  meunData: {
    type: Array as PropType<any>,
    default: () => []
  }
})
const newFaData = ref<any[]>([])

const schema = reactive<FormSchema[]>([
  {
    field: 'parent_id',
    label: '上级功能',
    component: 'TreeSelect',
    componentProps: {
      data: newFaData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'fa_id',
      props: {
        children: 'children',
        label: 'fa_name'
      }
    }
  },
  {
    field: 'fa_name',
    label: t('功能名称'),
    component: 'Input',
    formItemProps: {
      rules: [required]
    }
  },
  {
    field: 'fa_code',
    label: t('功能代码'),
    component: 'Input',
    formItemProps: {
      rules: [required]
    }
  },
  {
    field: 'disp_order',
    label: t('显示顺序'),
    component: 'InputNumber',
    componentProps: {
      min: 0
    }
  }
])

const { register, methods, elFormRef } = useForm({
  schema
})

watch(
  () => props.formData,
  (value) => {
    if (!value) return
    const { setValues } = methods
    setValues(value)
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props.meunData,
  (value) => {
    if (!value) return
    newFaData.value = [{ fa_id: '0', fa_name: '=== 顶级 ===' }, ...value]
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  elFormRef,
  getFormData: methods.getFormData,
  oldFormData: props.formData
})
</script>

<template>
  <Form @register="register" />
</template>
